package fun.eliauk.treedemo;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

/**
 * @author WangJing
 * @Description 脱敏工具类
 * @date 2021/6/19 1:39
 */
public class DesensitizedUtil {
 
 
    /**
     * 姓名脱敏
     * 规则：
     * 1、两位姓名，如：王京      置换为     王*
     * 2、大于两位，如：王京京     置换为    王*京
     *               王京京京   置换为    王*京
     * @param name
     * @return
     */
    private static String desensitizedName(String name){
        if(StringUtils.isNotEmpty(name)){
            if(name.length() == 2){
                name = name.replaceAll("(.).+", "$1*");
            }
            if(name.length() > 2){
                name = name.replaceAll("(.).+(.)", "$1*$2");
            }
        }
        return name;
    }
 
    /**
     * 手机号脱敏
     * 规则：保留前三后四，如：18812349876  置换为 188****9876
     * @param phone
     * @return
     */
    private static String desensitizedPhone(String phone){
        if(StringUtils.isNotEmpty(phone)){
            phone = phone.replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
        }
        return phone;
    }
 
    /**
     * 身份证脱敏（支持18位和15位）
     * 规则：保留前六后三，如：123456789987654321 置换为 123456*********321
     * @param idCard
     * @return
     */
    private static String desensitizedIdNumber(String idCard){
        if (StringUtils.isNotEmpty(idCard)) {
            if (idCard.length() == 15){
                idCard = idCard.replaceAll("(\\w{6})\\w*(\\w{3})", "$1******$2");
            }
            if (idCard.length() == 18){
                idCard = idCard.replaceAll("(\\w{6})\\w*(\\w{3})", "$1*********$2");
            }
        }
        return idCard;
    }
 
    public static void main(String[] args) {
        System.out.println("====  姓名脱敏  =====");
        String name2 = "王京";
        String name3 = "王京京";
        String name4 = "王京京京";
        System.out.printf("\n姓名：%s, 脱敏后：%s", name2, DesensitizedUtil.desensitizedName(name2));
        System.out.printf("\n姓名：%s, 脱敏后：%s", name3, DesensitizedUtil.desensitizedName(name3));
        System.out.printf("\n姓名：%s, 脱敏后：%s", name4, DesensitizedUtil.desensitizedName(name4));
 
        System.out.println("\n====  手机号脱敏  =====");
        String phone = "18812349876";
        System.out.printf("\n手机号：%s, 脱敏后：%s", phone, DesensitizedUtil.desensitizedPhone(phone));
 
        System.out.println("\n====  身份证脱敏  =====");
        String idCard = "123456789987654321";
        System.out.printf("\n身份证：%s, 脱敏后：%s", idCard, DesensitizedUtil.desensitizedIdNumber(idCard));
    }
 
}